<?php
/**
 * 接口调用封装方法
 */


if (!defined('IN_SEXMALL'))
{
	die('Hacking attempt');
}

/**
 * 获取档期列表
 */
function get_schedule(){
	global $mem, $mInterface;

	$schedule = $mem->getCache('shop_index_get');
	if (!is_array($schedule)){
		$result = $mInterface->getIndex();

		if ($result['status'] && is_array($result['result'])){
			$schedule = $result['result'];
		}

		foreach ($schedule AS $key => $val){
			switch ($val['link_type']){
				// 商品列表
				case 0 :
					$schedule[$key]['link'] = 'index.php?m=brand&id='.$val['id'];
					break;
				// 商品详情
				case 1 :
					$schedule[$key]['link'] = 'index.php?m=product&product_id='.$val['link'];
					break;
			}
		}

		$mem->addCache('shop_index_get', $schedule);
	}

	return $schedule;
}


/**
 * 获取分类
 */
function get_category()
{
	global $mem, $mInterface;

	$category = $mem->getCache('shop_category_get');
	if (!is_array($category))
	{
		$result = $mInterface->getCategory();
		if ($result['status'] && is_array($result['result']) ){
			$category = $result['result'];
		}else{
			$category = array();
		}

		$mem->addCache('shop_category_get', $category);
	}

	return $category;
}


/**
 * 获取用户信息
 * @param	string	$user_token	用户token
 */
function get_user_info($user_token)
{
	global $mem, $mInterface;

	if (empty($user_token)){
		return false;
	}

	$userInfo = $mem->getCache('shop_user_info');
	if (empty($userInfo['info']) || !is_array($userInfo['info']))
	{
		$userInfo = $mInterface->getUserBaseInfo($user_token);
		if ($userInfo['status'] && is_array($userInfo['result'])){
			$userInfo = $userInfo['result'];
		}

		$mem->addCache('shop_user_info', $userInfo);
	}

	return $userInfo;
}


/**
 * 取商品尺码
 * @param	int		$product_id		商品ID
 * @param	bool	$isFilter	是否过滤无库存尺码(true:过滤；false:不过滤)
 * @param	bool	$isCheck	是否选中第一个可用尺码(true:是；false:否)
 * @param	int		$type		类型：0为列表，1为详情（缓存生命周期不同）
 * @return	array()
 */
function get_product_sku($product_id, $isFilter=false, $isCheck=false, $type=0)
{
	global $mem, $mInterface;

	// 获取商品尺码
	$cache_name = ($type ? 'sexmall_product_detail_sku_' : 'sexmall_product_sku_').$product_id;
	$expire = $type ? DETAIL_SKU_CACHE_EXPIRE : SKU_CACHE_EXPIRE;
	$productSku = $mem->getCache($cache_name, true);
	if ( empty($productSku) || !is_array($productSku))
	{
		$productSku = $mInterface->getProductSku($product_id);
		$mem->addCache($cache_name, $productSku, $expire, true);
	}

	// 删除掉无库存尺码
	$selectedSku = array();	// 第一个可用的尺码
	$checked = false;	// 是否已经选中
	$product_leavings = 0;	// 商品剩余数量
	$stock_goods_num = 0;
	if (($isFilter || $isCheck) && !empty($productSku) && is_array($productSku))
	{
		foreach ((array)$productSku AS $k => $v)
		{
			if ($isFilter && $v['leavings'] < 1 && array_key_exists($k, $productSku) )
			{
				unset($productSku[$k]);
			}
			if ($isCheck && !$checked && $v['leavings'] > 0)
			{
				$productSku[$k]['checked'] = 1;
				$selectedSku = $v;
				$checked = true;
			}
			if ($isCheck && $v['leavings'] > 0){
				$stock_goods_num += 1;
			}

			$product_leavings += $v['leavings'];
		}
	}

	if ($stock_goods_num != 1){
		$selectedSku = array();
	}

	return array('sku'=>$productSku, 'selectedSku'=>$selectedSku, 'leavings'=>$product_leavings);
}


/**
 * 获取商品详情
 * @param	int	$product_id	商品ID
 * @return	array()	商品详情信息
 */
function get_product_info($product_id)
{
	global $mem, $mInterface;

	$productInfo = $mem->getCache('sexmall_product_detail_'.$product_id, true);
	if ( empty($productInfo) )
	{
		$productInfo = $mInterface->getProductDetail($product_id);
		$productInfo = $productInfo['result'];

		$mem->addCache('sexmall_product_detail_'.$product_id, $productInfo, PRODUCT_DETAIL_CACHE_EXPIRE, true);
	}

	return $productInfo;
}


/**
 * 获取商品列表
 * @param	int	$brand_id	品牌ID
 * @param	int	$cat_id		分类ID
 * @param	int	$filter_stock	是否过滤只显示有货商品
 */
function get_products_list($brand_id, $cat_id=0, $sort=0, $filter_stock=0)
{
	global $mem, $mInterface;

	// 取商品列表排序后的缓存
	$cache_filename = 'sexmall_brandProducts_'.$brand_id.'_' .$cat_id.'_' .$sort.'_' .$filter_stock;
	$goodslist = $mem->getCache($cache_filename, true);
	if (!is_array($goodslist))
	{
		// 从接口取默认排序商品列表
		$goodslist = $mem->getCache('sexmall_brandProducts_'.$brand_id.'_' .$cat_id.'_0_0', true);
		if (empty($goodslist) || !is_array($goodslist) || !$goodslist['result']['total'] || !$goodslist['result']['products']){
			$goodslist = $mInterface->getProductList($brand_id, $cat_id);
			$goodslist = $goodslist['result']['products'];

			$mem->addCache('sexmall_brandProducts_'.$brand_id.'_' .$cat_id.'_0_0', $goodslist, PRODUCT_LIST_CACHE_EXPIRE, true);
		}


		// 价格低至高 排序
		if ($sort == 1)
		{
			foreach ((array)$goodslist AS $key => $val)
			{
				$volume[$key]  = $val['imallPrice'];
			}
			if (!empty($volume))array_multisort($volume, SORT_ASC, $goodslist);
		}
		// 销量高至低 排序
		else if ($sort == 3)
		{
			foreach ((array)$goodslist AS $key => $val)
			{
				$volume[$key]  = floatval($val['agio']);
			}

			if (!empty($volume))array_multisort($volume, SORT_ASC, $goodslist);
		}

		// 只显示有货商品
		if ($filter_stock){
			foreach ((array)$goodslist AS $key => $val){
				if ($val['sale_out'] == 1){
					unset($goodslist[$key]);
				}
			}
		}

		// 写排序后的缓存
		$mem->addCache($cache_filename, $goodslist, PRODUCT_LIST_CACHE_EXPIRE, true);
	}

	return $goodslist;
}


/**
 * 获取支付方式
 * 有支付ID参数，返回该支付方式，否则返回所有支付方式列表
 * @param	int		$type		类型:1使用缓存，0不使用缓存
 * @param	int		$paytype_id	支付方式ID
 * @param	string	$user_token
 * @param	int		$address_id
 * @param	int		$order_amout
 * @param	bool	$order_all_supplier	是否全部供应商直发；true:过滤货到付款
 * @return	array
 */
function get_payment_list($type=1, $user_token='', $address_id=0, $order_amout=0, $paytype_id=0, $order_all_supplier=false)
{
	global $mem, $mInterface;

	/* 特殊活动，使用隐藏支付方式 */
	// 移动支付活动(只显示 货到付款和 移动手机支付)
	$credtential = wap_getcookie("WAP[credtential]");

	// 用户信息
	$user_blacklist = 0;
	if (!empty($user_token)){
		$userInfo = get_user_info($user_token);
		$user_blacklist = $userInfo['user_blacklist'];
	}

	// 根据需求：用户每天第4个订单以后不提供货到付款方式，每次从接口拿支付方式列表
	if ($type == 1){
		$payment_list = $mem->getCache('payment_list', true);
	}

	// 如果memcache缓存为空，则从接口获取
	if (empty($payment_list) || !is_array($payment_list))
	{
		if (!$type){
			$paymentList = $mInterface->getShopPayments($user_token, $address_id);

			// 实时接口返回空，尝试使用缓存列表
			if (empty($paymentList) || !is_array($paymentList)){
				$paymentList = $mem->getCache('payment_list', true);
			}
		}

		if (empty($paymentList) || !is_array($paymentList)){
			$paymentList = $mInterface->getShopPayments();
		}

		foreach ((array)$paymentList AS $key => $val)
		{
			// 货到付款
			if ($val['paytype_id'] == 8)
			{
				$payment_list[] = $val;
			}

			/* 在线支付 (49=移动支付；50=支付宝)*/
			if ( ($val['paytype_id'] == 49 && defined('OPEN_MOBILE_PAY') && OPEN_MOBILE_PAY != 'off')
			|| ($val['paytype_id'] == 50 && defined('OPEN_ALIPAY_PAY') && OPEN_ALIPAY_PAY != 'off') )
			{
				if ($val['paytype_id'] == 50){
					$paymentList[$key]['paytype_name'] = '支付宝';
				}

				$payment_list[] = $paymentList[$key];
			}
		}
		unset($paymentList);

		if ($type == 1){
			$mem->addCache('payment_list', $payment_list, PAYMENTLIST_CACHE_EXPIRE, true);
		}
	}


	// 黑名单过滤货到付款; 订单金额小于货到付款金额范围,则过滤货到付款
	// 移动支付活动(只显示 货到付款和 移动手机支付)
	if (!$type){
		foreach ($payment_list AS $key => $val){
			if ($val['paytype_id'] == 8 && ($order_all_supplier || $user_blacklist || ($order_amout && ($order_amout < COD_MONEY_MIN || COD_MONEY_MAX < $order_amout) ))){
				unset($payment_list[$key]);
			}

			else if ($val['paytype_id'] == 49 && defined('OPEN_MOBILE_PAY') && OPEN_MOBILE_PAY != 'on' && empty($credtential)){
				unset($payment_list[$key]);
			}

			else if ($val['paytype_id'] == 50 && !empty($credtential)){
				unset($payment_list[$key]);
			}
		}
	}

	// 返回指定的支付方式信息
	if ($paytype_id)
	{
		foreach ($payment_list AS $val){
			if ($paytype_id == $val['paytype_id']){
				return $val;
			}
		}
	}

	return $payment_list;
}


/**
 * 获取用户指定收货地址
 */
function get_one_address($mInterface, $user_token, $address_id=0)
{
	global $mem;

	$addressList = get_user_address_list($mInterface, $user_token);

	// 如果不完整则转向到收货人信息填写界面
	if (empty($addressList) || !is_array($addressList))
	{
		if (UI == 'default'){
			$back_act = 'index.php?m=flow&step=checkout';
			wap_setcookie("WAP[back_act]", $back_act);
			wap_header("Location: index.php?m=user&act=edit_address&step=add\n");
		}
		else
		{
			$back_act = 'flow-checkout.html';
			wap_setcookie("WAP[back_act]", $back_act);
			wap_header("Location: index.php?m=user&act=address&step=edit&filter=add");
		}
		exit;
	}

	$commonAddress = $consignee = array();
	$isCommon = false;

	// 获取用户指定地址
	foreach ((array)$addressList AS $key => $val)
	{
		if ( $address_id && $val['address_id'] == $address_id )
		{
			$consignee = $val;
			break;
		}

		// 获取默认地址
		if ($val['is_common'] == 1)
		{
			$commonAddress = $val;
		}
	}

	// 无用户指定地址，则用默认地址
	if (empty($consignee) && !empty($commonAddress) )
	{
		$consignee = $commonAddress;
	}
	else if (empty($consignee))
	{
		$consignee = array_shift($addressList);
	}


	//把"我不清楚"切掉 by james.wu
	$replace_arr = array("我不清楚" => "");
	$consignee['area_name'] =  strtr($consignee['area_name'],$replace_arr);

	return $consignee;
}


/**
 * 获取用户收货地址列表
 * @param	string	$user_token		用户token
 * @return	array()
 */
function get_user_address_list($mInterface, $user_token)
{
	global $mem;

	$address_list = $mInterface->getUserAddress($user_token);

	if (!$address_list['status'] || !is_array($address_list['result']))
	{
		$address_list = array();
	}else{
		$address_list = $address_list['result'];
	}

	foreach ($address_list AS $key => $val)
	{
		if (!is_array($val)){
			unset($address_list[$key]);
			continue;
		}

	}

	return $address_list;
}


/**
 * 获取用户默认收货地址
 * @param	object	$mInterface	接口对象
 * @param	string	$user_token	用户toekn
 */
function get_user_common_address($mInterface, $user_token)
{
	if (empty($user_token) )
	{
		return false;
	}

	// 从接口获取用户地址列表
	$address_list = get_user_address_list($mInterface, $user_token);

	$consignee = array();
	$isCommon = false;
	if (is_array($address_list) && !empty($address_list))
	{
		foreach ((array)$address_list AS $key => $val)
		{
			if ($val['is_common'] == 1)
			{
				$consignee = $address_list[$key];
				break;
			}
		}

		if (empty($consignee))
		{
			$consignee = $address_list[0];
		}
	}

	return $consignee;
}


/**
 * 品牌分类信息
 */
function get_brand_category($brand_id, $cat_id=0)
{
	return false;

	global $mInterface, $mem;

	$cat_name = '';
	$cur_cat = array();

	$brand_category = $mem->getCache('sexmall_brandCategory_' . $brand_id, true);
	if (empty($brand_category) || !is_array($brand_category))
	{
		$brand_category = $mInterface->getBrandCategory($brand_id);
		$mem->addCache('sexmall_brandCategory_'.$brand_id, $brand_category, BRAND_CATEGORY_CACHE_EXPIRE, true);
	}

	// 获取指定分类的ID、名称
	if ($cat_id)
	{
		foreach ($brand_category AS $val)
		{
			if ($val['cat_id'] == $cat_id)
			{
				//$cat_name = $val['cat_name'];
				$cur_cat = $val;
				break;
			}
		}
	}

	return array('categorys'=>$brand_category, 'cur_cat'=>$cur_cat);
}


/**
 * 获取服务器时间,将时间差缓存到本地文件中
 */
function  get_serverTime()
{
	global $mInterface;
	$mytime= $_SERVER['REQUEST_TIME'];

	$key='ServerTimespan';
	//读取缓存中的时间差,默认5分钟一次
	$timespan = read_static_cache($key, 3600, 0, true);
	if ( (empty($timespan)&&$timespan!=0) || !is_numeric($timespan))
	{
		// 获取服务器时间
		$server_time = $mInterface->getUtilsTime ();
		// 兼容正式、测试环境获取服务器时间接口
		if (is_array ( $server_time ) && array_key_exists ( 'time', $server_time )) {
			$server_time = $server_time ['time'];
		}
		$timespan=$server_time -$mytime;
		write_static_cache($key, $timespan, true);

		$mytime=$server_time;
	}
	else
	{
		$mytime=$mytime+$timespan;
	}

	return $mytime;
}

/**
 * 获取用户留意列表
 * @param unknown $user_token
 * @param unknown $uname
 */
function getFeedbackListFrom($user_token, $uname)
{
	//return getFeedbackListFromDb($user_token,$uname);
	return getFeedbackListFromServer($user_token,$uname);
}

/**
 * 获取用户留言列表
 * @param unknown $user_token
 * @param unknown $uname
 */
function getFeedbackListFromDb($user_token,$uname)
{
	global $mem, $mInterface, $db;
	if($uname)
	{
		$sql = "SELECT * FROM ".TABLEPRE."feedback WHERE yz=0 AND uname='$uname' ORDER BY addtime DESC";
		$fd_ls = $db->getAll($sql);
		$fd_num = count($fd_ls);
		foreach($fd_ls as $k=>$v)
		{
			$fd_ls[$k]['fid'] = $fd_num;
			$fd_ls[$k]['addtime'] = date('Y-m-d H:i:s', $v['addtime']);
			if($v['retime']>0)$fd_ls[$k]['retime'] = date('Y-m-d H:i:s', $v['retime']);
			$fd_num--;
		}

		return $fd_ls;
	}

	return array();
}


/**
 * 从服务器获取留言列表
 * @param unknown $user_token
 * @param unknown $uname
 */
function getFeedbackListFromServer($user_token, $uname)
{
	global $mem, $mInterface;
	$datas=$mInterface->getUserMessageList($user_token);
	$ren=array();

	if($datas)
	{
		$fd_num = count($datas);
		foreach ($datas as $d)
		{
			$t=array();
			$t["fid"]=$fd_num;
			$t["addtime"]= date('Y-m-d H:i:s', $d['add_time']);
			$t["content"]=$d["content"];
			$fd_num--;

			$msg=$mInterface->getUserMessageDetail($user_token,$d["message_id"]);
			if($msg && $msg["reply"] && count($msg["reply"])>0)
			{
				$replay=$msg["reply"];

				foreach ($replay as $k=>$r)
				{
					$replay[$k]["addtime"]= date('Y-m-d H:i:s', $r['add_time']);
				}
				$t["reply"]=$replay;
			}
			$ren[]=$t;
		}
	}

	return $ren;
}